import axios from 'axios'
import { decrypt } from '@/utils/util'

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  withCredentials: false,
})

// request interceptor
instance.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

// response interceptor
instance.interceptors.response.use(
  response => {
    const res = response.data
    // 如果自定义code不为0，则将其判断为错误。
    // if (res.code !== undefined && res.code !== 0) {
    //   // TODO

    //   // 50008: 非法的token; 50012: 其他客户端登录了; 50014: Token 过期了;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // TODO
    //   }
    //   return Promise.reject(new Error(res.message || 'System Error'))
    // }
    if(!res.code){
      response.data = JSON.parse(decrypt(res));
    }
    return response;
  },
  error => {
    if (error.response.status === 509) {
      let html = error.response.data;
      let verifyWindow = window.open("","_blank","height=400,width=560");
      verifyWindow.document.write(html);
      verifyWindow.document.getElementById("baseUrl").value = import.meta.env.VITE_APP_BASE_API;
    }
    return error
  },
)

// if (import.meta.env.PROD) {
//   const mockAdapter = new MockAdapter(instance, { delayResponse: 500 })
//   MockApi(mockAdapter)
// }

export default instance
